from flask import flash, current_app, redirect, url_for, request, render_template
from flask_login import login_required, current_user

from apps.models.drift import Drift
from apps.models.gift import Gift
from apps.utils.enum import PendingStatus
from apps.view_models.gift_wish import GiftWishViewModel
from . import web
from apps.models.base import db


@web.route('/my/gifts')
@login_required
def my_gifts():
    gifts = Gift.query.filter_by(uid=current_user.id, launched=False).all()
    isbn_list = [gift.isbn for gift in gifts]
    gift_wish_counts = Gift.get_user_gift(isbn_list)
    view_model = GiftWishViewModel(gifts, gift_wish_counts)
    return render_template('my_gifts.html', gifts=view_model.books)


@web.route('/gifts/book/<isbn>')
@login_required
def save_to_gifts(isbn):
    if current_user.save_to_gift(isbn):
        with db.auto_commit():
            gift = Gift()
            gift.isbn = isbn
            gift.uid = current_user.id
            current_user.beans += current_app.config['GIFT_OR_WISH_BEANS']
            db.session.add(gift)
    else:
        flash('添加失败')
    return redirect(url_for('web.book_detail', isbn=isbn))


@web.route('/gifts/<gid>/redraw')
@login_required
def redraw_from_gifts(gid):
    gift = Gift.query.get_or_404(gid)
    if Drift.query.filter_by(gift_id=gid, pending=PendingStatus.waiting).first():
        flash('有鱼漂尚还在进行中，请完成处理！')
        return redirect(url_for('web.pending'))
    with db.auto_commit():
        gift.delete()
        current_user.beans -= current_app.config['GIFT_OR_WISH_BEANS']
    return redirect(url_for('web.my_gifts'))


